import TagsApi from '@lib/api/tags';
import { Select } from 'antd';
import * as React from 'react';

interface TagInputProps {
	value: string[];
	onChange: (tags: string[]) => void;
}

interface TagInputState {
	value: string[];
	tag: string[];
}

class TagInput extends React.Component<TagInputProps, TagInputState> {
	private handleChange: (value: string[]) => void;
	private handleSearch: (value: string) => void;
	private timer: number;
	constructor(props: any) {
		super(props);
		this.state = {
			tag: [],
			value: []
		};
		this.timer = -1;
		this.handleChange = this._handleChange.bind(this);
		this.handleSearch = this._handleSearch.bind(this);
	}

	componentWillReceiveProps(props: any) {
		if (typeof (props.value) !== "undefined") {
			this.setState({
				value: props.value
			});
		}
	}

	public _handleChange(value: string[]) {
		this.setState({
			value
		});
		this.props.onChange(value);
	}

	public _handleSearch(value: string) {
		this.setState({
			tag: []
		});
		if (this.timer !== -1) {
			window.clearTimeout(this.timer);
			this.timer = -1;
		}
		this.timer = window.setTimeout(() => {
			TagsApi(value).then(res => {
				if (!(res instanceof Error)) {
					this.setState({
						tag: res.list
					});
				}
				window.clearTimeout(this.timer);
				this.timer = -1;
			});
		}, 500);
	}

	render() {
		const tags = this.state.tag.map(it => <Select.Option value={it} key={it}>{it}</Select.Option>)
		return (
			<Select
				mode="tags"
				style={{ width: '100%' }}
				onSearch={this.handleSearch}
				onChange={this.handleChange}
				tokenSeparators={[',']}
				value={this.state.value}>
				{tags}
			</Select>
		)
	}


}

export default TagInput;